<template>
  <div style="width: 50%">
    <div class="card" style="padding: 30px">
      <el-form :model="user" label-width="100px" style="padding-right: 50px">
        <div style="margin: 20px 0; text-align: center">
          <el-upload :show-file-list="false" class="avatar-uploader" :action="uploadUrl" :on-success="handleFileUpload">
            <img v-if="user.avatar" :src="user.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <el-form-item label="账号">
          <el-input disabled v-model="user.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="user.name" autocomplete="off" />
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      // user: JSON.parse(localStorage.getItem('system-user') || '{}'),
      user: {
        username: 'admin',
        name: '管理员'
      },
      uploadUrl: process.env.VUE_APP_BASE_URL + '/files/upload',
    };
  },
  methods: {
    handleFileUpload(file) {
      this.user.avatar = file.data;
    },
    save() {
      if (this.user.role === 'ADMIN') {
        request.put('/admin/update', this.user).then(res => {
          if (res.code === '200') {
            this.$message.success('更新成功');
            // 把更新后的用户信息存储到缓存
            localStorage.setItem('system-user', JSON.stringify(this.user));
            this.$emit('updateUser');
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },
  },
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>